package com.dianjing.dianjing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dianjing.dianjing.controller.UploadController;
import com.dianjing.dianjing.dto.input.LoginInput;
import com.dianjing.dianjing.dto.input.UserInfoUpdateInput;
import com.dianjing.dianjing.dto.input.UserInput;
import com.dianjing.dianjing.dto.output.PainterShowOutput;
import com.dianjing.dianjing.dto.output.UserOutput;
import com.dianjing.dianjing.entity.Painting;
import com.dianjing.dianjing.entity.User;
import com.dianjing.dianjing.entity.UserCollection;
import com.dianjing.dianjing.enums.CollectionTypeEnum;
import com.dianjing.dianjing.enums.SysMessage;
import com.dianjing.dianjing.mapper.UserMapper;
import com.dianjing.dianjing.service.PaintingService;
import com.dianjing.dianjing.service.UserCollectionService;
import com.dianjing.dianjing.service.UserService;
import com.dianjing.dianjing.util.DataUtils;
import com.dianjing.dianjing.util.ResponseData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author owf
 * @Date 2022/11/8
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UploadController uploadController;

    @Resource
    private UserMapper userMapper;

    @Resource
    private PaintingService paintingService;

    @Resource
    private UserCollectionService userCollectionService;
    /**
     * 登录功能
     *
     * @param input
     * @return
     */
    @Override
    public ResponseData login(LoginInput input) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, input.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            return ResponseData.fail(SysMessage.LOGIN_FAIL_USER_NOT_EXIST.getMsg());
        }
        if (!user.getPassword().equals(input.getPassword())) {
            return ResponseData.fail(SysMessage.LOGIN_FAIL_PASSWORD.getMsg());

        }
        return ResponseData.success().data(JSONUtil.parse(user));
    }

    /**
     * 注册功能
     *
     * @param input
     * @return
     */
    @Override
    public ResponseData register(UserInput input) {
        //校验两次输入的密码
        if (!input.getPassword().equals(input.getPasswordVerify())) {
            System.out.println("再次输入的密码一样");
            return ResponseData.fail(SysMessage.REGISTER_FAIL_PASSWORD_ERROR.getMsg());
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, input.getUsername());
        User dbUser = userMapper.selectOne(queryWrapper);
        //校验用户名是否已被使用
        if (Objects.nonNull(dbUser)) {
            System.out.println("已存在用户");
            return ResponseData.fail(SysMessage.REGISTER_FAIL_NAME_USED.getMsg());
        }
        User user = new User();
        BeanUtil.copyProperties(input, user);
        userMapper.insert(user);
        return ResponseData.success().data(JSONUtil.parse(user));
    }

    @Override
    public Boolean updateUserInfo(UserInfoUpdateInput userInfoUpdateInput) {
        // 上传文件，得到url
        String url = uploadController.MultipartFileToUrl( userInfoUpdateInput.getHeadImg());
        User user = baseMapper.selectById(userInfoUpdateInput.getId());
        // 如果上传返回的url不为空才能进行覆盖 headerUrl
        if(user != null && url != null) {
            user.setHeaderUrl(url);
        }
        BeanUtils.copyProperties(userInfoUpdateInput,user);
        int i = baseMapper.updateById(user);
        return i > 0;
    }

    @Override
    public List<PainterShowOutput> seeTypePainters(Long typeId) {
        // 获取作品类型为 typeId 的所有作品
        LambdaQueryWrapper<Painting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(typeId != null,Painting::getType,typeId);
        List<Painting> paintings = paintingService.list(wrapper);
        // 将得到key为画师id,value为画师作品的集合
        HashMap<Long, List<Painting>> painterAndWorks = new HashMap<>(16);
        for (Painting painting : paintings) {
            Long painterId = painting.getPainterId();
            // 查看是否已经有画师对应的元素
            List<Painting> existValue = painterAndWorks.get(painterId);
            if(existValue == null) {
                // 还没有
                ArrayList<Painting> value = new ArrayList<>();
                value.add(painting);
                painterAndWorks.put(painterId,value);
            }else {
                // 已经有了
                existValue.add(painting);
            }
        }
        // 将 （key为画师id,value为画师作品的集合） =>  List<PainterShowOutput> key-value放在 PainterShowOutput对象中
        ArrayList<PainterShowOutput> newContainer = new ArrayList<>();
        Set<Long> painterIds = painterAndWorks.keySet();
        for (Long key : painterIds) {
            List<Painting> value = painterAndWorks.get(key);
            PainterShowOutput newItem = new PainterShowOutput();
            newItem.setId(key);
            newItem.setPaintings(value);
            newContainer.add(newItem);
        }

        if (painterIds == null || painterIds.size() == 0 ) {
            return newContainer;
        }
        // 分别获取这些画师的详情信息
        List<User> users = baseMapper.selectBatchIds(painterIds);
        for (User painterData : users) {
            // 遍历新容器
            for (PainterShowOutput newItem : newContainer) {
                if(newItem.getId().equals(painterData.getId())) {
                    // 将画师详情的信息填充到newItem中画师的信息
                    BeanUtils.copyProperties(painterData,newItem);
                    break;
                }
            }
        }
        return newContainer;
    }

    @Override
    public List<UserOutput> collectPainter(int userId) {
        // 选出收藏的画师，得到收藏的画师id集合
        QueryWrapper<UserCollection> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserCollection::getUserId,userId)
                        .eq(UserCollection::getType, CollectionTypeEnum.TYPE_PAINTER.getType());
        List<UserCollection> collects = userCollectionService.list(wrapper);
        List<Long> painterIds = collects.stream().map(collect -> collect.getCollectionId()).collect(Collectors.toList());
        if (painterIds == null || painterIds.size() < 1) {
            return new ArrayList<UserOutput>();
        }
        // 批量查询画师信息
        List<User> painters = baseMapper.selectBatchIds(painterIds);
        // 映射为输出类别
        List<UserOutput> userOutputs = painters.stream().map((painter) -> {
            UserOutput userOutput = new UserOutput();
            BeanUtils.copyProperties(painter, userOutput);
            return userOutput;
        }).collect(Collectors.toList());
        return userOutputs;
    }

    @Override
    public DataUtils alterPassword(Long userId, String oldPassword, String newPassword) {
        // 先判断使用旧密码+用户id 是否能查询到用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId,userId).eq(User::getPassword,oldPassword);
        User user = baseMapper.selectOne(wrapper);
        if(user != null) {
            // 存在用户，且密码与id对应上，可以进行修改
            user.setPassword(newPassword);
            int i = baseMapper.updateById(user);
            if(i >= 1) {
                // 修改成功
                return DataUtils.ok("修改成功");
            }else {
                // 修改失败
                return DataUtils.error("密码未修改！");
            }
        }else {
            return DataUtils.error("旧密码错误！",null);
        }

    }


}
